/**
 * 所有版权归 广西梧州 陈锦韬 所有
 *
 * @Title: SensitiveInfoSerialize
 * @Package com.rx.core.data
 * @Description: 脱敏序列化类
 * @author: 陈锦韬
 * @date: 2020\9\9 0009
 * @version V1.0
 * @Copyright: 2020 陈锦韬  All rights reserved.
 */
package com.rx.core.dbase;

import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.rx.core.base.RxBaseData;
import com.rx.core.bean.RxConfigBean;
import com.rx.core.enm.SENSITIVE_TYPE;
import com.rx.core.util.EmptyChecker;
import com.rx.core.util.RxUtil;
import com.rx.core.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author: Administrator
 * @Description: 脱敏序列化类
 * @date: 2020\9\9 0009
 */
@Slf4j
public class SensitiveInfoSerialize extends JsonSerializer<String> implements ContextualSerializer, ValueFilter, PropertyFilter {

    private List<String> filterFieldList = new ArrayList<>();
    private SENSITIVE_TYPE type;
    public SensitiveInfoSerialize() {
    }

    public SensitiveInfoSerialize(final SENSITIVE_TYPE type) {
        this.type = type;
    }
    /**
     * [中文姓名] 只显示第一个汉字，其他隐藏为2个星号<例子：李**>
     */
    public static String chineseName(final String fullName) {
        if (StringUtils.isBlank(fullName)) {
            return "";
        }
        final String name = StringUtils.left(fullName, 1);
        return StringUtils.rightPad(name, StringUtils.length(fullName), "*");
    }

    /**
     * [中文姓名] 只显示第一个汉字，其他隐藏为2个星号<例子：李**>
     */
    public static String chineseName(final String familyName, final String givenName) {
        if (StringUtils.isBlank(familyName) || StringUtils.isBlank(givenName)) {
            return "";
        }
        return chineseName(familyName + givenName);
    }

    /**
     * [身份证号] 显示最后四位，其他隐藏。共计18位或者15位。<例子：*************5762>
     */
    public static String idCardNum(final String id) {
        if (StringUtils.isBlank(id)) {
            return "";
        }

        return StringUtils.left(id, 3).concat(StringUtils
                .removeStart(StringUtils.leftPad(StringUtils.right(id, 3), StringUtils.length(id), "*"),
                        "***"));
    }

    /**
     * [固定电话] 后四位，其他隐藏<例子：****1234>
     */
    public static String fixedPhone(final String num) {
        if (StringUtils.isBlank(num)) {
            return "";
        }
        return StringUtils.leftPad(StringUtils.right(num, 4), StringUtils.length(num), "*");
    }

    /**
     * [手机号码] 前三位，后四位，其他隐藏<例子:138******1234>
     */
    public static String mobilePhone(final String num) {
        if (StringUtils.isBlank(num)) {
            return "";
        }
        return StringUtils.left(num, 2).concat(StringUtils
                .removeStart(StringUtils.leftPad(StringUtils.right(num, 2), StringUtils.length(num), "*"),
                        "***"));

    }

    /**
     * [地址] 只显示到地区，不显示详细地址；我们要对个人信息增强保护<例子：北京市海淀区****>
     *
     * @param sensitiveSize 敏感信息长度
     */
    public static String address(final String address, final int sensitiveSize) {
        if (StringUtils.isBlank(address)) {
            return "";
        }
        final int length = StringUtils.length(address);
        return StringUtils.rightPad(StringUtils.left(address, length - sensitiveSize), length, "*");
    }

    /**
     * [电子邮箱] 邮箱前缀仅显示第一个字母，前缀其他隐藏，用星号代替，@及后面的地址显示<例子:g**@163.com>
     */
    public static String email(final String email) {
        if (StringUtils.isBlank(email)) {
            return "";
        }
        final int index = StringUtils.indexOf(email, "@");
        if (index <= 1) {
            return email;
        } else {
            return StringUtils.rightPad(StringUtils.left(email, 1), index, "*")
                    .concat(StringUtils.mid(email, index, StringUtils.length(email)));
        }
    }

    /**
     * [银行卡号] 前六位，后四位，其他用星号隐藏每位1个星号<例子:6222600**********1234>
     */
    public static String bankCard(final String cardNum) {
        if (StringUtils.isBlank(cardNum)) {
            return "";
        }
        return StringUtils.left(cardNum, 6).concat(StringUtils.removeStart(
                StringUtils.leftPad(StringUtils.right(cardNum, 4), StringUtils.length(cardNum), "*"),
                "******"));
    }

    /**
     * [公司开户银行联号] 公司开户银行联行号,显示前两位，其他用星号隐藏，每位1个星号<例子:12********>
     */
    public static String cnapsCode(final String code) {
        if (StringUtils.isBlank(code)) {
            return "";
        }
        return StringUtils.rightPad(StringUtils.left(code, 2), StringUtils.length(code), "*");
    }

    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
        switch (this.type) {
            case CHINESE_NAME: {
                jsonGenerator.writeString(chineseName(s));
                break;
            }
            case ID_CARD: {
                jsonGenerator.writeString(idCardNum(s));
                break;
            }
            case FIXED_PHONE: {
                jsonGenerator.writeString(fixedPhone(s));
                break;
            }
            case MOBILE_PHONE: {
                jsonGenerator.writeString(mobilePhone(s));
                break;
            }
            case ADDRESS: {
                jsonGenerator.writeString(address(s, 4));
                break;
            }
            case EMAIL: {
                jsonGenerator.writeString(email(s));
                break;
            }
            case BANK_CARD: {
                jsonGenerator.writeString(bankCard(s));
                break;
            }
            case CNAPS_CODE: {
                jsonGenerator.writeString(cnapsCode(s));
                break;
            }
            default:
                jsonGenerator.writeString(s);
                break;
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty != null) {
            // 为空直接跳过
            if (Objects.equals(beanProperty.getType().getRawClass(), String.class)) {
                // 非 String 类直接跳过
                SensitiveInfo sensitiveInfo = beanProperty.getAnnotation(SensitiveInfo.class);
                if (sensitiveInfo == null) {
                    sensitiveInfo = beanProperty.getContextAnnotation(SensitiveInfo.class);
                }
                if (sensitiveInfo != null) {
                    // 如果能得到注解，就将注解的 value 传入 SensitiveInfoSerialize
                    return new SensitiveInfoSerialize(sensitiveInfo.value());
                }
            }
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }
        return serializerProvider.findNullValueSerializer(beanProperty);

    }

    @Override
    public Object process(Object object, String name, Object value) {
        if (null == value || !(value instanceof String) || ((String) value).length() == 0) {
            return value;
        }
        try {
            Field field = RxUtil.Reflection.getField(object.getClass(),name);
            SensitiveInfo desensitization;
            if (String.class != field.getType() || (desensitization = field.getAnnotation(SensitiveInfo.class)) == null) {
                return value;
            }
            switch (desensitization.value()) {
                case CHINESE_NAME: {
                    value=chineseName((String)value);
                    break;
                }
                case ID_CARD: {
                    value=idCardNum((String)value);
                    break;
                }
                case FIXED_PHONE: {
                    value=fixedPhone((String)value);
                    break;
                }
                case MOBILE_PHONE: {
                    value=mobilePhone((String)value);
                    break;
                }
                case ADDRESS: {
                    value=address((String)value, 4);
                    break;
                }
                case EMAIL: {
                    value=email((String)value);
                    break;
                }
                case BANK_CARD: {
                    value=bankCard((String)value);
                    break;
                }
                case CNAPS_CODE: {
                    value=cnapsCode((String)value);
                    break;
                }
                default:

                    break;
            }
        } catch (NoSuchFieldException e) {
            log.warn("ValueDesensitizeFilter the class {} has no field {}", object.getClass(), name);
        }
        return value;
    }

    @Override
    public boolean apply(Object object, String name, Object value) {
        List<String> tmpAddList=null;
        List<String> tmpRemoveList=null;
        if(object instanceof RxBaseData){
            tmpAddList = (List<String>) ((RxBaseData)object).getTmpVar(RxBaseData.VAR_JSON_FILTER);
            tmpRemoveList = (List<String>) ((RxBaseData)object).getTmpVar(RxBaseData.VAR_JSON_REMOVE_FILTER);
        }
        if (EmptyChecker.isEmpty(filterFieldList)){
            RxConfigBean rxConfigBean = (RxConfigBean) SpringUtil.getBean("rxConfigBean");
            if(EmptyChecker.isEmpty(rxConfigBean) && EmptyChecker.isEmpty(tmpAddList)){
                return true;
            }

            filterFieldList = Arrays.asList(rxConfigBean.getJsonFilterFields().split(","));
            if (EmptyChecker.isEmpty(filterFieldList) && EmptyChecker.isEmpty(tmpAddList)){
                return true;
            }
        }

        if (EmptyChecker.isEmpty(tmpAddList)){
            tmpAddList = new ArrayList<>(filterFieldList);
        }else if(EmptyChecker.notEmpty(tmpAddList)){
            tmpAddList.addAll(filterFieldList);
        }
        if (EmptyChecker.notEmpty(tmpRemoveList)){
            tmpAddList.removeAll(tmpRemoveList);
        }
        /**
         * 字段过滤
         */
        for (String s : tmpAddList) {
            if(s.equalsIgnoreCase(name)){
                return false;
            }
        }
        return true;
    }
}
